<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>活动管理</el-breadcrumb-item>
      <el-breadcrumb-item>活动列表</el-breadcrumb-item>
      <el-breadcrumb-item>活动详情</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card style="margin-top: 30px">
      <!-- 搜索 -->
      <el-row :gutter="20">
        <el-col :span="10">
          <el-input
            placeholder="请输入内容"
            clearable
            @clear="searchuser"
            v-model="queryInfo.query"
            @input="searchuser"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="searchuser"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="14">
          <el-button type="primary" @click="adduser">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 表格 -->
      <el-table border style="margin-top: 15px" :data="userlist">
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <div>
              <el-switch
                v-model="scope.row.mg_state"
                @change="userstate(scope.row)"
              ></el-switch>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <div>
              <!-- 修改 -->
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="edituser(scope.row)"
              ></el-button>
              <!-- 删除 -->
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="deleteuser(scope.row.id)"
              ></el-button>
              <!-- 角色 -->
              <el-button
                type="warning"
                icon="el-icon-s-tools"
                size="mini"
                @click="setUserRoleDia(scope.row)"
              ></el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 页码 -->
      <div class="block">
        <el-pagination
          style="margin-top: 15px"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pagenum"
          :page-sizes="[2, 4, 5, 8]"
          :page-size="queryInfo.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
      <!--添加弹框 -->
      <el-dialog title="添加" :visible.sync="dialogVisible">
        <span slot="footer" class="dialog-footer">
          <el-form ref="adduserref" :rules="rules" :model="fomdata">
            <el-form-item label-width="80px" label="姓名" prop="username">
              <el-input v-model="fomdata.username"></el-input>
            </el-form-item>
            <el-form-item label-width="80px" label="密码" prop="password">
              <el-input v-model="fomdata.password"></el-input>
            </el-form-item>
            <el-form-item label-width="80px" label="邮箱" prop="email">
              <el-input v-model="fomdata.email"></el-input>
            </el-form-item>
            <el-form-item label-width="80px" label="电话" prop="mobile">
              <el-input v-model="fomdata.mobile"></el-input>
            </el-form-item>
          </el-form>
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="qd">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 编辑弹框 -->
      <el-dialog title="编辑" :visible.sync="edituserdiao">
        <span slot="footer" class="dialog-footer">
          <el-form ref="edituserref" :rules="editrules" :model="fomdata">
            <el-form-item label-width="80px" label="姓名" prop="username">
              <el-input v-model="fomdata.username" disabled></el-input>
            </el-form-item>
            <el-form-item label-width="80px" label="邮箱" prop="email">
              <el-input v-model="fomdata.email"></el-input>
            </el-form-item>
            <el-form-item label-width="80px" label="电话" prop="mobile">
              <el-input v-model="fomdata.mobile"></el-input>
            </el-form-item>
          </el-form>
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editqd">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 角色弹框 -->
      <el-dialog title="分配角色" :visible.sync="isSetUserRoleDia" width="40%">
        <div>
          <p>
            当前用户：<span>{{ currentUser.username }}</span>
          </p>
          <p>
            当前角色：<span>{{ currentUser.role_name }}</span>
          </p>
          <span class="mr10">分配新角色:---{{ currentRoleId }}</span>
          <el-select v-model="currentRoleId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </div>

        <span slot="footer" class="dialog-footer">
          <el-button @click="isSetUserRoleDia = false">取 消</el-button>
          <el-button type="primary" @click="setUserRoleOK">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import _ from "lodash";
import {
  getUserListApi,
  getUserAdd,
  getuserstate,
  getuserEdit,
} from "@/http/api";
export default {
  name: "user",
  data() {
    // 邮箱的验证方法
    const checkMail = (rule, value, callback) => {
      // 邮箱正则
      const emailReg =
        /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,5}$/;
      if (!emailReg.test(value)) {
        return callback(new Error("邮箱规则不正确，请检查并重新输入"));
      }
      // 满足验证规则
      callback();
    };

    // 邮箱的验证方法
    const checkMobile = (rule, value, callback) => {
      // 邮箱正则
      const mobilelReg = /^1[3456789]\d{9}$/;
      if (!mobilelReg.test(value)) {
        return callback(new Error("手机号格式不正确，请检查并重新输入"));
      }
      // 满足验证规则
      callback();
    };
    return {
      //选择的新角色id
      currentRoleId: "",
      //角色列表
      rolesList: [],
      //是否显示分配角色对话框
      isSetUserRoleDia: false,
      //当前用户id
      currentUserId: 0,
      //当前用户对象
      currentUser: {},
      // 是否显示分配角色对话框
      isrolesdaio: false,
      // 是否显示编辑对话框
      edituserdiao: false,
      // 是否显示添加对话框
      dialogVisible: false,
      value: "",
      // 用户查询信息
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 5,
      },
      // 添加 编辑公用表单对象
      fomdata: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      // 用户列表数据
      userlist: [],
      // 用户总条数
      total: 0,
      // 编辑用户验证规则
      editrules: {
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkMail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入电话", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
      // 添加用户验证规则
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 5,
            max: 10,
            message: "长度在 5 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 5,
            max: 10,
            message: "长度在 5 到 10 个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkMail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入电话", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    // 确认分配角色
    async setUserRoleOK() {
      //调用分配角色接口
      const res = await this.$API.getusersrole(
        this.currentUserId,
        this.currentRoleId,
      );
       console.log("分配新角色ok:", this.currentUserId, this.currentRoleId);
      //隐藏分配角色对话框
      this.isSetUserRoleDia = false;
         //更新用户列表
      this.getUserList()
     
    },
    //打开分配角色对话框
    async setUserRoleDia(row) {
      console.log("打开的用户信息", row);
      this.currentRoleId = true;
      //解构获取用户名和角色名
      const { id, username, role_name } = row;
      this.currentUserId = id;
      //将用户名和角色名赋值给当前用户对象currentUser
      this.currentUser = { username, role_name };
      //获取所有可能的角色列表接口
      const res = await this.$API.getusersroles();
      console.log("返回角色列表：", res);
      this.rolesList = res;
      //隐藏分配角色对话框
      this.isSetUserRoleDia = true;
    },
    // 状态
    async userstate(row) {
      const res = await getuserstate(row.id,row.mg_state);
      console.log("改变状态返回的结果：", res);
      this.getUserList()
    },
    // 删除
    async deleteuser(id) {
      const res = await this.$confirm(
        "此操作将永久删除该文件，是否继续？",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((error) => {
        this.$message({
          type: error,
          message: "已取消删除",
        });
      });
      if (res === "confirm") {
        await this.$API.getuserdelete(id);
        this.getUserList();
      }
    },
    // 编辑确定
    editqd() {
      this.$refs.edituserref.validate(async (vaild) => {
        if (!vaild) return;
        const res = await getuserEdit(this.currentuserid, this.fomdata);
        console.log(res);
        this.edituserdiao = false;
        this.getUserList();
      });
    },
    // 编辑
    edituser(row) {
      this.fomdata = {};
      this.currentuserid = row.id;
      const { username, email, mobile } = row;
      this.fomdata = { username, email, mobile };
      this.edituserdiao = true;
    },
    // 搜索
    searchuser: _.debounce(function () {
      this.getUserList();
    }, 300),
    // 添加列表
    qd() {
      //检验表单是否符合规则
      this.$refs.adduserref.validate(async (vaild) => {
        if (!vaild) return;
        const res = await getUserAdd(this.fomdata);
        this.dialogVisible = false;
        this.getUserList();
      });
    },
    // 添加用户对框
    adduser() {
      this.fomdata = {};
      this.dialogVisible = true;
    },
    // 每条页数改变时，就会触发
    handleSizeChange(val) {
      console.log(val);
      this.queryInfo.pagesize = val;
      this.getUserList();
    },
    // 当前页码改变时就会触发
    handleCurrentChange(val) {
      console.log(val);
      this.queryInfo.pagenum = val;
      this.getUserList();
    },
    //
    async getUserList() {
      const res = await getUserListApi(this.queryInfo);
      console.log(res);
      let { total, users } = res;
      this.userlist = users;
      this.total = total;
    },
  },
};
</script>

<style lang="scss" scoped>
.users {
  background: #eaedf1;
  height: 100%;
}
</style>